#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速端口清理工具 - 一键强制关闭8000-8010端口的程序
"""

import subprocess
import sys
import time


def quick_clean_ports():
    """快速清理8000-8010端口的程序"""
    print("正在快速清理8000-8010端口...")

    killed_count = 0

    # 查找所有占用8000-8010端口的进程
    for port in range(8000, 8011):
        # 使用netstat查找占用端口的进程
        cmd = f'netstat -ano | findstr ":{port} "'
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

        if result.stdout.strip():
            lines = result.stdout.strip().split('\n')
            for line in lines:
                if f':{port}' in line and any(state in line for state in ['LISTENING', 'ESTABLISHED']):
                    parts = line.split()
                    if len(parts) >= 5:
                        pid = parts[-1]
                        try:
                            # 强制终止进程
                            subprocess.run(['taskkill', '/F', '/PID', pid],
                                         check=True, capture_output=True)
                            print(f"[OK] 已终止占用端口 {port} 的进程 PID {pid}")
                            killed_count += 1
                        except subprocess.CalledProcessError:
                            print(f"[ERROR] 终止进程 PID {pid} 失败")

    # 额外清理Python进程
    try:
        # 查找Python进程
        cmd = 'tasklist /FI "IMAGENAME eq python.exe" /FO CSV /NH'
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

        if result.stdout.strip():
            lines = result.stdout.strip().split('\n')
            for line in lines:
                if line.strip():
                    parts = line.split(',')
                    if len(parts) >= 2:
                        pid = parts[1].strip('"')
                        # 检查是否可能是我们的程序
                        try:
                            # 获取进程命令行
                            cmd_line = subprocess.run(
                                ['wmic', 'process', 'where', f'processid={pid}', 'get', 'commandline', '/value'],
                                capture_output=True, text=True
                            )
                            if '800' in cmd_line.stdout or 'uvicorn' in cmd_line.stdout or 'fastapi' in cmd_line.stdout:
                                subprocess.run(['taskkill', '/F', '/PID', pid],
                                             check=True, capture_output=True)
                                print(f"[OK] 已终止相关Python进程 PID {pid}")
                                killed_count += 1
                        except:
                            pass
    except:
        pass

    print(f"\n清理完成！共终止 {killed_count} 个进程")

    # 验证清理结果
    print("\n验证清理结果...")
    time.sleep(2)

    still_occupied = []
    for port in range(8000, 8011):
        cmd = f'netstat -ano | findstr ":{port} "'
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

        if result.stdout.strip():
            lines = result.stdout.strip().split('\n')
            for line in lines:
                if f':{port}' in line and any(state in line for state in ['LISTENING', 'ESTABLISHED']):
                    still_occupied.append(port)
                    break

    if still_occupied:
        print(f"[WARNING] 以下端口仍被占用: {still_occupied}")
    else:
        print("[OK] 所有端口已完全释放！")


if __name__ == "__main__":
    try:
        print("=" * 50)
        print("快速端口清理工具 v1.0")
        print("=" * 50)
        quick_clean_ports()
    except KeyboardInterrupt:
        print("\n\n操作被用户中断")
    except Exception as e:
        print(f"\n程序运行出错: {e}")